// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.designer.ui.database.figures;

import java.util.ArrayList;
import java.util.List;

import org.dengues.commons.IDenguesSharedImage;
import org.dengues.commons.utils.ColorUtil;
import org.dengues.commons.utils.ImageUtil;
import org.dengues.model.database.DBColumn;
import org.dengues.model.database.DBTable;
import org.dengues.model.database.EMFDataType;
import org.eclipse.draw2d.Button;
import org.eclipse.draw2d.ButtonModel;
import org.eclipse.draw2d.ChangeEvent;
import org.eclipse.draw2d.ChangeListener;
import org.eclipse.draw2d.CheckBox;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.ImageFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.ScrollPane;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.util.EList;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 1 2006-09-29 17:06:40Z qiang.zhang $
 * 
 */
public class DBTableCustomFigure extends GenericFigure {

    private static final Image COLLAPSE_IMAGE = ImageUtil.getImage(IDenguesSharedImage.EDITOR_COLLAPSEALL);

    private static final Image EXPAND_IMAGE = ImageUtil.getImage(IDenguesSharedImage.EDITOR_EXPANDALL);

    public static final Color BG_COLOR = new Color(null, 50, 100, 180);

    public static final Color START_COLOR = new Color(null, new RGB(0xB0, 0xE7, 0));

    private DBColumnPaneFigure columnPaneFigure;

    private Label tableName;

    private final DBTable dbTable;

    private final ToolbarLayout toolbarLayout;

    private Figure titleFigure;

    private int i = 0;

    public DBTableCustomFigure(DBTable castModel) {
        this.dbTable = castModel;
        setBorder(new org.eclipse.draw2d.MarginBorder(2, 3, 7, 7));
        toolbarLayout = new ToolbarLayout();
        toolbarLayout.setVertical(true);
        setLayoutManager(toolbarLayout);
        setBorder(new LineBorder(ColorConstants.black, 1));
        setOpaque(true);
        setForegroundColor(ColorConstants.gray);
        createContents();
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "createContents".
     */
    private void createContents() {
        ScrollPane columnsPane = new ScrollPane();
        columnPaneFigure = new DBColumnPaneFigure();
        columnsPane.getViewport().setContents(columnPaneFigure);

        tableName = new Label();
        tableName.setText(dbTable.getName());
        Font erFont = new Font(null, "Arial", 12, SWT.BOLD); //$NON-NLS-1$
        tableName.setFont(erFont);
        tableName.setForegroundColor(ColorConstants.darkBlue);
        titleFigure = new Figure();
        titleFigure.setOpaque(false);
        org.eclipse.draw2d.FlowLayout myGenLayoutManager = new org.eclipse.draw2d.FlowLayout();
        myGenLayoutManager.setStretchMinorAxis(true);
        myGenLayoutManager.setMinorAlignment(org.eclipse.draw2d.FlowLayout.ALIGN_CENTER);
        myGenLayoutManager.setMajorAlignment(org.eclipse.draw2d.FlowLayout.ALIGN_LEFTTOP);
        myGenLayoutManager.setMajorSpacing(5);
        myGenLayoutManager.setMinorSpacing(5);
        myGenLayoutManager.setHorizontal(true);
        titleFigure.setLayoutManager(myGenLayoutManager);
        final int emfType = dbTable.getDbDiagram().getEmfType().getValue();
        switch (emfType) {
        case EMFDataType.QUERY_VALUE:
            final CheckBox checkBox = new CheckBox();
            checkBox.setSelected(dbTable.isSelected());
            checkBox.addChangeListener(new ChangeListener() {

                /*
                 * (non-Javadoc)
                 * 
                 * @see org.eclipse.draw2d.ChangeListener#handleStateChanged(org.eclipse.draw2d.ChangeEvent)
                 */
                public void handleStateChanged(ChangeEvent event) {
                    if (event.getPropertyName().equals(ButtonModel.SELECTED_PROPERTY)) {
                        dbTable.setSelected(checkBox.isSelected());
                        EList columns = dbTable.getColumns();
                        for (Object object : columns) {
                            ((DBColumn) object).setSelected(checkBox.isSelected());
                        }
                    }
                }
            });
            titleFigure.add(checkBox);
            break;

        }
        titleFigure.add(new ImageFigure(ImageUtil.getImage(IDenguesSharedImage.VIEW_TABLE)));
        titleFigure.add(tableName);

        Image image = dbTable.isHidden() ? EXPAND_IMAGE : COLLAPSE_IMAGE;
        final Button button = new Button(image);
        button.setRolloverEnabled(true);
        button.addChangeListener(new ChangeListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.draw2d.ChangeListener#handleStateChanged(org.eclipse.draw2d.ChangeEvent)
             */
            public void handleStateChanged(ChangeEvent event) {
                if (event.getPropertyName().equals(ButtonModel.PRESSED_PROPERTY)) {
                    List children2 = button.getChildren();
                    i++;
                    for (Object object2 : children2) {
                        if (object2 instanceof Label) {
                            Label label = (Label) object2;
                            if (i % 2 == 0) {
                                if (EXPAND_IMAGE.equals(label.getIcon())) {
                                    label.setIcon(COLLAPSE_IMAGE);
                                    for (DBColumn column : getColumns()) {
                                        column.setHidden(false);
                                    }
                                } else {
                                    label.setIcon(EXPAND_IMAGE);
                                    for (DBColumn column : getColumns()) {
                                        column.setHidden(true);
                                    }
                                }
                                i = 0;
                            }
                        }
                    }
                }
            }
        });
        titleFigure.add(button);
        add(titleFigure);
        add(columnsPane);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getColumns".
     * 
     * @return
     */
    private List<DBColumn> getColumns() {
        EList columns = dbTable.getColumns();
        final List<DBColumn> extCols = new ArrayList<DBColumn>();
        for (DBColumn column2 : dbTable.getColumns()) {
            extCols.add(column2);
        }
        return extCols;
    }

    @Override
    protected void fillShape(Graphics graphics) {
        Rectangle r = getBounds();
        Rectangle.SINGLETON.setBounds(r);
        Rectangle.SINGLETON.y += 1;
        Rectangle.SINGLETON.height -= 1;

        int shadowDepth = getShadow();
        int rectangleWidth = r.width - shadowDepth;
        int rectangleHeight = r.height - shadowDepth;

        Color foreground = graphics.getForegroundColor();
        Color background = graphics.getBackgroundColor(), shadow = ColorUtil.darker(foreground);

        int x = r.x + shadowDepth;
        int y = r.y + shadowDepth;

        /**
         * trace shadow
         */
        for (int i = shadowDepth - 1; i >= 0; i--) {
            shadow = lighter(background, i + 1, shadowDepth + 1);
            graphics.setBackgroundColor(shadow);
            graphics.fillRectangle(x, y, rectangleWidth, rectangleHeight);
            if (i > 0) {
                x--;
                y--;
            }
        }

        graphics.setBackgroundColor(background);
        graphics.setForegroundColor(foreground);

        graphics.fillRectangle(x, y, rectangleWidth, rectangleHeight);
        // Gradient
        graphics.setForegroundColor(foreground);
        graphics.fillGradient(x, y - 20, rectangleWidth, tableName.getBounds().height + 25, true);
        graphics.setForegroundColor(foreground);

        graphics.drawRectangle(x, y, rectangleWidth, rectangleHeight);
    }

    @Override
    protected void outlineShape(Graphics graphics) {

    }

    /**
     * Getter for columnPaneFigure.
     * 
     * @return the columnPaneFigure
     */
    public DBColumnPaneFigure getColumnPaneFigure() {
        return this.columnPaneFigure;
    }

    /**
     * Getter for tableName.
     * 
     * @return the tableName
     */
    public Label getTableName() {
        return this.tableName;
    }

    /**
     * Getter for titleFigure.
     * 
     * @return the titleFigure
     */
    public Figure getTitleFigure() {
        return this.titleFigure;
    }
}
